<?php
$to = $_POST["to"];
$subject = $_POST["subject"];
$message = $_POST["message"];

// 邮件模板处理
$template = $_POST["template"];
if ($template == "template1") {
$message = str_replace("[NAME]", "张三", $message);
} else if ($template == "template2") {
$message = str_replace("[NAME]", "李四", $message);
}

// 附件处理
if ($_FILES["attachment"]["error"] == UPLOAD_ERR_OK) {
$attachment = $_FILES["attachment"];
$attachmentName = $attachment["name"];
$attachmentTempName = $attachment["tmp_name"];
$attachmentType = $attachment["type"];
$attachmentSize = $attachment["size"];
$attachmentContent = file_get_contents($attachmentTempName);
}

// 发送邮件
foreach ($to as $recipient) {
// 根据安全性处理进行过滤
if (isBlacklist($recipient)) {
continue;
}
if (!isWhitelist($recipient)) {
continue;
}

$headers = "";
if (!empty($attachmentContent)) {
// 带附件发送
$mimeBoundary = md5(time());
$headers .= "MIME-Version: 1.0\r
";
$headers .= "Content-Type: multipart/mixed; boundary=" . $mimeBoundary . "\r
";
$messageBody = "--" . $mimeBoundary . "\r
";
$messageBody .= "Content-Type: text/plain; charset=utf-8\r
";
$messageBody .= "Content-Transfer-Encoding: 8bit\r
\r
";
$messageBody .= $message . "\r
\r
";
$messageBody .= "--" . $mimeBoundary . "\r
";
$messageBody .= "Content-Type: " . $attachmentType . "; name=\"" . $attachmentName . "\"\r
";
$messageBody .= "Content-Transfer-Encoding: base64\r
";
$messageBody .= "Content-Disposition: attachment; filename=\"" . $attachmentName . "\"\r
\r
";
$messageBody .= chunk_split(base64_encode($attachmentContent)) . "\r
\r
";
$messageBody .= "--" . $mimeBoundary . "--\r
";
} else {
// 普通文本邮件发送
$headers .= "Content-Type:text/plain;charset=utf-8\r
";
$headers .= "From:sender@example.com\r
";
}

$success = mail($recipient, $subject, $messageBody, $headers);
if (!$success) {
echo "发送邮件失败！";
exit;
}
echo "发送成功！";
}

// 黑名单
function isBlacklist($email) {
$blacklist = ["spam@example.com", "junk@mail.com"];
return in_array($email, $blacklist);
}

// 白名单
function isWhitelist($email) {
$whitelist = ["user1@example.com", "user2@example.com"];
return in_array($email, $whitelist);
}
